package com.link.base.base.message.push.service;

import com.link.base.base.message.push.model.PushInfo;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.RedisUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Component;

import com.oppo.push.server.Notification;
import com.oppo.push.server.Result;
import com.oppo.push.server.Sender;
import com.oppo.push.server.Target;

/**
 * OPPO推送
 *
 * @author ouyangzhenqiang
 * @date 2019/08/12 16:08
 */
@Component
public class OppoPushServiceImpl {

    /**
     * 推送消息
     *
     * @author ouyangzhenqiang
     * @date 2019/08/12 16:08
     */
    void oppoPush(PushInfo record) throws Exception {
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            String redisKey = "APP_PUSH_CONFIG";
            String oppoPushAppKey = j.hget(redisKey, "oppoPushAppKey_" + record.getAppId());
            String oppoPushMasterSecret = j.hget(redisKey, "oppoPushMasterSecret_" + record.getAppId());
            Sender sender = new Sender(oppoPushAppKey, oppoPushMasterSecret);
            // 发送单推通知栏消息
            Notification notification = getNotification(record);
            // 创建发送对象
            Target target = Target.build(record.getPushServiceToken());
            // 发送单推消息
            Result result = sender.unicastNotification(notification, target);
            LCLogger.info().withMessageKey("oppoPush").withMessage("sendPush result => " + result).flush();
            if (!(result.getReturnCode().getCode() == 0 && "Success".equals(result.getReturnCode().getMessage()))) {
                throw new BasicServiceException(result.getReturnCode().getMessage());
            }
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    /**
     * 构造消息体
     * @author liyongfeng
     * @date 2019/06/13
     */
    private static Notification getNotification(PushInfo record) {
        Notification notification = new Notification();
        notification.setTitle(record.getPushTitle());
        notification.setContent(record.getPushNote());
        return notification;
    }

}
